package com.teradata.multithread.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: lyndon
 * @version: 1.0
 * @date: 2019/2/24
 */
public class FixThreadPoolReturnDemo implements Callable<String> {

    private int num;

    static ExecutorService executorService = Executors.newFixedThreadPool(3);

    public FixThreadPoolReturnDemo(int num) {
        this.num = num;
    }

    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "---" + this.num;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        final ConcurrentSkipListSet<Future<String>> taskRes = new ConcurrentSkipListSet<>();

        for (int i = 0; i < 20; i++) {
            Future<String> stringFuture = executorService.submit(new FixThreadPoolReturnDemo(i));
            taskRes.add(stringFuture);
        }
        System.out.println(taskRes.size());

        List<String> resSet = new ArrayList<>();

        for (;;) {
            if (taskRes.size() == 0) {
                break;
            }
            for (Future taskRe : taskRes) {
                if (taskRe.isDone()) {
                    resSet.add((String) taskRe.get());
                    taskRes.remove(taskRe);
                }
            }
        }

        for (String s : resSet) {
            System.out.println(s);
        }

        executorService.shutdown();
    }


}
